JS 中通过 bind
绑定的方法,再使用 apply
或 call
会改变它的 this
吗
- 不会
js
var a = {
name: "a",
getName: function () {
return this.name;
},
};
var b = {
name: "b",
getName: function () {
return this.name;
},
};
var c = {
name: "c",
getName: function () {
return this.name;
},
};
// console.log(a.getName.call(b)); // b
// console.log(a.getName.bind(b)()); // b
Function.prototype._call = function (context) {
const key = Symbol();
context[key] = this;
const result = context[key]();
delete context[key];
return result;
};
// console.log(a.getName._call(b)); // b
Function.prototype._bind = function (context, ...args) {
const fn = this;
return function F() {
// bind 返回的是一个函数,函数可能被 new, 作为构造函数被调用
if (this instanceof F) {
return new fn(...args, ...arguments); //等价于 new dog.getDog()
}
return fn._call(context, args.concat(...arguments)); // b
};
};
// console.log(a.getName._bind(b)()); // b
const f = a.getName.bind(b);
console.log(f.call(c)); //
js
function a() {
console.log("a");
}
function b() {
console.log("b");
}
a.call.call(b); // 'b'
Function.prototype._call = function (context) {
// context = b
const key = Symbol();
context[key] = this; // this = call, 关键点多个 call.call.call 中 this 指向 call
const result = context[key](); // b.call() 就是执行b
delete context[key];
return result;
};